import pandas as pd

import ClickHouseApi
import numpy as np
import json
import os
def cula(author_name):
    collaborate=ClickHouseApi.Select_Repos_Pr_AllCounts(author_name)#获取合作
    pr_count=ClickHouseApi.Select_Pr_Count(author_name)#pr次数
    review_count=ClickHouseApi.Select_Pr_ReView_Count(author_name)#回复次数
    interaction=pr_count+review_count#总的互动次数
    if collaborate==0:
        A2=0
    else:
        A2=interaction/collaborate
    AS1=AInterval(collaborate)
    AS2=AInterval(A2)
    return AS1,AS2


def criticW(AS1,AS2):
    if(len(AS1)==0 or len(AS2)==0 or len(AS1)==1 or len(AS2)==1):
        return 0.5279,0.4721
    data={'AS1':AS1,
          'A2':AS2}

    df=pd.DataFrame(data)
    X=df.values
    #极差归一化处理
    X_norm=(X-X.min(axis=0))/(X.max(axis=0)-X.min(axis=0))

    #确定权重
    sigma=np.std(X_norm,axis=0)
    corr=np.corrcoef(X_norm.T)
    C=sigma*np.sum(1-corr,axis=0)
    weights=C/np.sum(C)
    return weights

def AInterval(A1):
    if A1<3:
        AS1=10
    elif(A1>=3 and A1 <5):
        AS1=20
    elif(A1>=5 and A1<10):
        AS1=30
    elif(A1>=10 and A1<30):
        AS1=50
    elif(A1>=30 and A1<50):
        AS1=80
    elif(A1>=50 and A1<100):
        AS1=100
    elif (A1>=100 and A1<150):
        AS1=150
    else:
        AS1=200
    return AS1

def calcW(numbers):
    authors=ClickHouseApi.Select100_Name(numbers)
    AS1S=[]
    AS2S=[]
    for author in authors:
        AS1,AS2=cula(author)
        AS1S.append(AS1)
        AS2S.append(AS2)
    W1,W2=criticW(AS1S, AS2S)
    with open('weight.json','w+') as f:
        data={'W1':W1,'W2':W2}
        json_data=json.dumps(data)
        f.write(json_data)
    return W1,W2


def model(author_name,numbers=10):
    if os.path.exists('weight.json'):
        with open('weight.json','r+') as f:
            data=json.load(f)
    else:
        calcW(numbers)
    f1,f2=cula(author_name)
    return f1*data['W1']+f2*data['W2']


print(model('tomayac'))

# calcW(10)


